package client_V2;
// <editor-fold defaultstate="collapsed" desc="Imports">
import lib.FileHandler;
import lib.StreamSocket;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
// </editor-fold>

/**
 * @file Receiver.java
 *
 * @version 0.1
 * @author Chris Sewell 10008342
 */
public class Receiver extends Thread {
    // <editor-fold defaultstate="collapsed" desc="Attributes">

    StreamSocket serverStream;
    String serverInput;
    FileHandler file;
    int length;
    int fileServerPort;
    String host;
    byte[] data;
    Socket fileRequest;
    ClientDataTransferThread dx;
// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Constructors">

    public Receiver(StreamSocket serverStream, String host) {
        this.serverStream = serverStream;
        this.host = host;
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Methods">

    @Override
    public void run() {
        while (true) {
            serverInput = serverStream.recieveString();
            if (serverInput == null) {//If null string received kill connection from server
                try {                    
                    serverStream.kill();
                } catch (IOException ex) {
                    Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, null, ex);
                }
                return;
            }
            if (serverInput.equals("Valid")) {//If valid string received then begin file transfer from server
                serverInput = serverStream.recieveString();//get file name
                length = Integer.parseInt(serverStream.recieveString());//get size of file
                file = new FileHandler(serverInput, length); //Create file
                fileServerPort = Integer.parseInt(serverStream.recieveString());//get port
                try {
                    fileRequest = new Socket(host, fileServerPort);//Request file socket
                    StreamSocket downloadSocket = new StreamSocket(fileRequest);
                    dx = new ClientDataTransferThread(downloadSocket, length, file);//Set up file transfer thread
                    dx.start();
                } catch (UnknownHostException ex) {
                    Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, null, ex);
                }
                serverInput = serverStream.recieveString();
            }
            System.out.println(serverInput);
        }
    }
    // </editor-fold> 
}
